package com.yds.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.util.Log

class BLEDataWriter {

    companion object {
        private const val TAG = "YDSimon"
    }

    private var mGatt: BluetoothGatt? = null
    fun sendDataToAllWritableCharacteristics(gatt: BluetoothGatt?, data: ByteArray) {
        mGatt = gatt
        val services = mGatt!!.services
        for (service in services) {
            val characteristics = service.characteristics
            for (characteristic in characteristics) {
                if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE != 0) {
                    tryToSendData(characteristic, data)
                }
            }
        }
    }

    private fun tryToSendData(characteristic: BluetoothGattCharacteristic, data: ByteArray) {
        characteristic.value = data
        @SuppressLint("MissingPermission") val success = mGatt!!.writeCharacteristic(characteristic)
        if (success) {
            Log.i(TAG, "Data sent to characteristic: " + characteristic.uuid)
        } else {
            Log.e(TAG, "Failed to send data to characteristic: " + characteristic.uuid)
        }
    }


}